package com.learning.netease.optimize.snowslide;

import com.google.common.base.Strings;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.concurrent.TimeUnit;

/**
 * ClassName: CacheSnowSlideService
 * Description: 缓存雪崩解决方案
 * Date: 2019/1/21 10:43 【需求编号】
 *
 * @author Sam Sho
 * @version V1.0.0
 */
@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
public class CacheSnowSlideService {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private com.learning.cache.redis.snowslide.DataDao dataDao;


    public String doService(String name) {

        // 1- 先从Redis 缓存获取数据
        String result = redisTemplate.opsForValue().get(name);

        if (!Strings.isNullOrEmpty(result)) {
            log.info(Thread.currentThread().getName() + " 缓存中取得数据 ---------> " + result);
            return result;
        }

        // 2- 缓存中没有，则取数据库
        result = dataDao.get(name);
        System.out.println(Thread.currentThread().getName() + " 从数据库中中取得数据 ============> " + result);


        // 3- 更新缓存，120秒超时
        redisTemplate.opsForValue().set(name, result, 120, TimeUnit.SECONDS);

        return result;
    }
}
